package com.salud.mendoza;

import java.io.IOException;
import java.nio.file.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

    public static void main(String[] args) {
        try {
            String directorio = args[0];
            WatchService watcher = FileSystems.getDefault().newWatchService();

            Path dir = Paths.get(directorio);
            dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
            while (true) {
                WatchKey key;
                try {
                    // wait for a key to be available
                    key = watcher.take();
                } catch (InterruptedException ex) {
                    return;
                }

                for (WatchEvent<?> event : key.pollEvents()) {
                    // get event type
                    WatchEvent.Kind<?> kind = event.kind();

                    // get file name
                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();

                    System.out.println(kind.name() + ": " + fileName);

                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        String nombre = fileName.toFile().getName();
                        String extensionArchivo = ".csv";
                        if (!nombre.substring(nombre.length() - extensionArchivo.length(), nombre.length()).equals(extensionArchivo)) {
                            try {
                                IfaceConverter.procesar(directorio + "/" + fileName.toString());
                            } catch (Exception e) {
                                System.out.println("Error al procesar el archivo " + e.getMessage());
                            }
                        }
                    }

                }

                // IMPORTANT: The key must be reset after processed
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
